package com.zj.config;

import com.zj.enu.SqlType;
import com.zj.mapping.Configration;
import com.zj.mapping.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configration configration;

    private String namespace;

    public XMLMapperBuilder(Configration configration) {
        this.configration=configration;
    }

    public void parseMapper(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        namespace = rootElement.attributeValue("namespace");
        parseStatement(rootElement,SqlType.INSERT);
        parseStatement(rootElement,SqlType.DELETE);
        parseStatement(rootElement,SqlType.UPDATE);
        parseStatement(rootElement,SqlType.SELECT);

    }

    private void parseStatement(Element rootElement, SqlType type){
        List<Element> selectElements = rootElement.selectNodes("//"+type.getValue());
        for (Element selectElement : selectElements) {
            String id = selectElement.attributeValue("id");
            String resultType = selectElement.attributeValue("resultType");
            String paramterType = selectElement.attributeValue("paramterType");
            String sql = selectElement.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlType(type);

            configration.getMappedStatementMap().put(namespace+"."+id,mappedStatement);
        }
    }
}
